<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="layui/css/layui.css" media="all">
</head>
<script src="layui/layui.js" charset="utf-8"></script>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
  <legend>菜单分配</legend>
</fieldset>

<div id="test1" class="demo-tree demo-tree-box"></div>
<div class="layui-btn-container" style="float:right">
  <button type="button" class="layui-btn layui-btn-sm" lay-demo="getChecked" style="text-align:right">确定</button>
</div>
<script type="text/javascript">
  function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);//search,查询？后面的参数，并匹配正则
    if (r != null) return unescape(r[2]);
    return null;
  }

  layui.use(['tree', 'util'], function () {
    var tree = layui.tree,
      util = layui.util;
    var $ = layui.$;
    var id = GetQueryString("id");
    var ajaxData = "id=" + id;
    $.ajax({
      type: "post",
      data: ajaxData,
      url: "menuJson",
      success: function (data) {
        start(tree, data);
      }
    })


    //渲染
    function start(tree, data) {
      tree.render({
        elem: '#test1'  //绑定元素
        , data: data
        , id: "demo1"
        , showCheckbox: "true"
      });
    }

    util.event('lay-demo', {
      getChecked: function (othis) {
        var checkedData = tree.getChecked('demo1'); //获取选中节点的数据
        var menuId = getId(checkedData);
        var ajaxData2 = "roleId=" + id + "&menuId=" + menuId;
        $.ajax({
          type: "post",
          data: ajaxData2,
          url: "menuCheck",
          success: function (data) {
            layer.alert(data.message);
            layer.close(layer.index);
            window.parent.location.reload();
          }
        })
      }
    });
  });

  function getId(data) {
    var id = new Array();
    for (var i = 0; i < data.length; i++) {
      id.push(data[i].id);
      if (data[i].children != undefined) {
        var id2 = getId(data[i].children);
        id = id.concat(id2);
      }
    }
    console.log(id)
    return id;
  }


</script>
</body>
</html>